<template>
  <div style="width:100%">
    <div class="my-chart" ref="myChart" :style="{height:height,width:width}"></div>
  </div>
</template>

<script type="text/ecmascript-6">
  import {debounce} from "@/utils/debounce";
  // // 按需引入
  // // 引入基本模板
  // let echarts = require('echarts/lib/echarts');
  // // 引入线组件
  // require('echarts/lib/chart/line');
  // // 引入提示框和title组件
  // require('echarts/lib/component/tooltip');
  // require('echarts/lib/component/title');

  // 全部引入
  // var echarts = require('echarts');
  import echarts from "echarts";

  export default {
    name: "BaseEcharts",
    data() {
      return {
        chart: null,
        resizeHandler: null
      };
    },
    props: {
      option: {
        type: Object,
        default: null
      },
      width: {
        type: String,
        default: "100%"
      },
      height: {
        type: String,
        default: "2rem"
      },
      clear: {
        type: Boolean,
        default: false
      },
      isLoading: {
        type: Boolean,
        default: false
      }
    },
    mounted() {
      this.initCharts();
    },
    destroyed() {
      window.removeEventListener("resize", this.resizeHandler);
    },
    methods: {
      initCharts() {
        this.chart = echarts.init(this.$refs.myChart);
        this.setOption(this.option);
        // 用于监听页面大小变化，自动适应
        this.resizeHandler = debounce(() => {
          if (this.chart) {
            this.chart.resize();
          }
          if (this.animationstart) {
            this.animationstart = false;
            this.$refs.myChart.removeEventListener("animationstart", this.resizeHandler);
          }
        }, 100);
        this.$refs.myChart.addEventListener("animationstart", this.resizeHandler);
        this.animationstart = true;
        window.addEventListener("resize", this.resizeHandler);
      },
      setOption(option) {
        if (option) {
          if (this.clear) {
            this.chart.clear();
          }
          this.chart.setOption(option);
        }
      }
    },
    watch: {
      option(newV) {
        this.setOption(newV);
      },
      isLoading(newV) {
        if (newV) {
          this.chart.showLoading();
        } else {
          this.chart.hideLoading();
        }
      }
    }
  };
</script>
<style lang="less">
  .my-chart {
    animation: myfirst 0.1s;
  }

  @keyframes myfirst {
    0% {
      opacity: 0;
    }
    100% {
      opacity: 0;
    }
  }
</style>
